<template>
  <el-button @click="onDelete" :disabled="disabled" type="primary">
    {{ $t('lang.operate.delete') }}
  </el-button>
</template>

<script lang="ts">
import { ObjectType } from 'typings/interfaces'
import { defineComponent, PropType, computed } from 'vue'
import { isEmpty, map, get } from 'lodash'
import { ElMessageBox, ElMessage } from 'element-plus'
import { useI18n } from 'vue-i18n'

export default defineComponent({
  emit: ['update:selectedRows'],
  props: {
    selectedRows: {
      type: Array as PropType<ObjectType[]>,
      required: true,
    },
    valuePath: {
      type: String,
      default: 'id',
    },
    requestData: {
      type: Function as PropType<(...args: any) => Promise<any>>,
      required: true,
    },
    updateData: {
      type: Function as PropType<(jumpFirstPage: boolean) => void>,
      required: true,
    },
    beforeConfirm: {
      type: Function as PropType<(...args: any) => Promise<any>>,
      required: false,
      default: () => new Promise((resolve) => resolve(true)),
    },
    // 只能删除草稿状态数据
    justDeleteDraft: {
      type: Boolean,
      required: false,
      default: false,
    },
  },
  setup(props, { emit }) {
    const { t } = useI18n()
    const onDelete = () => {
      if (props.justDeleteDraft) {
        for (let i = 0; i < props.selectedRows.length; i++) {
          const e = props.selectedRows[i]
          if (e.status != 0) {
            ElMessage.error('只能删除草稿状态的数据！')
            return
          }
        }
      }
      const params = map(props.selectedRows, (item) => get(item, props.valuePath))
      ElMessageBox.confirm(t('lang.operate.isDelete'), t('lang.operate.hint'), {
        confirmButtonText: t('lang.operate.confirm'),
        cancelButtonText: t('lang.operate.cancel'),
        type: 'warning',
      }).then(() => {
        props.requestData(params).then(() => {
          emit('update:selectedRows', [])
          props.updateData(true)
        })
      })
    }
    return {
      disabled: computed(() => isEmpty(props.selectedRows)),
      onDelete,
    }
  },
})
</script>
